import { useState, useEffect } from 'react'
import apiService from '../utils/api.js'
import SongCard from '../components/SongCard.jsx'
import AddToPlaylistModal from '../components/AddToPlaylistModal.jsx'
import '../styles/pages.css'

function Home({ playSong }) {
  const [dailyRecommendations, setDailyRecommendations] = useState([])
  const [topSongs, setTopSongs] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [showAddToPlaylistModal, setShowAddToPlaylistModal] = useState(false)
  const [selectedSong, setSelectedSong] = useState(null)

  // 获取每日推荐歌曲
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        
        // 获取每日推荐歌曲
        const dailyResponse = await apiService.getDailyRecommendations({limit: '4'})
        if (dailyResponse.code === 200 && dailyResponse.data) {
          setDailyRecommendations(dailyResponse.data)
        }
        
        // 获取热门榜单歌曲
        const topResponse = await apiService.getTopSongs({limit: '5'})
        if (topResponse.code === 200 && topResponse.data) {
          setTopSongs(topResponse.data)
        }
      } catch (err) {
        console.error('获取数据失败:', err)
        setError('获取数据失败')
        // 使用模拟数据
        setDailyRecommendations([])
        setTopSongs([])
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  // 打开添加到歌单模态框
  const openAddToPlaylistModal = (song) => {
    setSelectedSong(song)
    setShowAddToPlaylistModal(true)
  }

  // 关闭添加到歌单模态框
  const closeAddToPlaylistModal = () => {
    setShowAddToPlaylistModal(false)
    setSelectedSong(null)
  }

  // 添加歌曲到歌单成功后的回调函数
  const handleAddToPlaylistSuccess = () => {
    // 可以在这里添加成功后的额外逻辑
    console.log('歌曲成功添加到歌单')
  }

  // 播放歌曲 - 从props接收的playSong函数已经实现了核心功能
  // 当前函数保持不变以兼容已有的调用方式，但会被props中的同名函数覆盖
  // 实际播放逻辑在App.jsx中实现

  return (
    <div className="home-page">
      <div className="section-header">
        <h2>每日推荐</h2>
      </div>
      
      {error && (
        <div className="error-message">
          {error}
          <button onClick={() => setError('')}>×</button>
        </div>
      )}
      
      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <div className="song-grid">
          {dailyRecommendations.map((song) => (
            <SongCard 
              key={song.id} 
              song={song} 
              onClick={playSong}
              onAddToPlaylist={openAddToPlaylistModal}
            />
          ))}
        </div>
      )}
      
      <div className="section-header" style={{ marginTop: '40px' }}>
        <h2>热门榜单</h2>
      </div>
      
      <div className="chart-container">
        <div className="chart-card">
          <h3>飙升榜</h3>
          <div className="chart-list">
            {loading ? (
              Array(5).fill(0).map((_, index) => (
                <div key={index} className="chart-item loading">
                  <span className="rank-number">{index + 1}</span>
                  <span className="chart-song-title">加载中...</span>
                </div>
              ))
            ) : (
              topSongs.length > 0 ? (
                topSongs.map((song, index) => (
                  <div 
                    key={song.id} 
                    className="chart-item" 
                    onClick={() => playSong(song)}
                  >
                    <span className="rank-number">{index + 1}</span>
                    <span className="chart-song-title">{song.title}</span>
                    <span className="chart-song-artist">{song.artist.name}</span>
                  </div>
                ))
              ) : (
                Array(5).fill(0).map((_, index) => (
                  <div key={index} className="chart-item">
                    <span className="rank-number">{index + 1}</span>
                    <span className="chart-song-title">暂无数据</span>
                    <span className="chart-song-artist">暂无歌手</span>
                  </div>
                ))
              )
            )}
          </div>
        </div>
      </div>

      {/* 添加到歌单模态框组件 */}
      <AddToPlaylistModal
        visible={showAddToPlaylistModal}
        onClose={closeAddToPlaylistModal}
        onAddSuccess={handleAddToPlaylistSuccess}
        selectedSong={selectedSong}
      />
    </div>
  )
}

export default Home